<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Search, Refresh } from '@element-plus/icons-vue'
// 配置axios的基础URL为/api，利用vite代理解决跨域问题
import axios from 'axios'
axios.defaults.baseURL = '/api'

// 搜索表单
const searchForm = reactive({
  name: '',
  label: ''
})

// 表格数据
const tableData = ref([])

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 20
})

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formData = reactive({
  id: '',
  name: '',
  label: '',
  remark: ''
})

// 重置表单
const resetForm = () => {
  // 重置搜索表单
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  // 重置编辑表单
  formData.id = ''
  formData.name = ''
  formData.label = ''
  formData.remark = ''
  // 清空后自动查询列表
  queryRoleList()
}

// 序号生成方法，从1开始
const indexMethod = (index) => {
  return (pagination.currentPage - 1) * pagination.pageSize + index + 1
}

// 查询角色列表
const queryRoleList = async () => {
  try {
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    
    // 移除空字符串参数
    Object.keys(params).forEach(key => {
      if (params[key] === '') {
        delete params[key]
      }
    })
    
    const response = await axios.get('/roles', { params })
    if (response.data.code === 1) {
      tableData.value = response.data.data.rows
      pagination.total = response.data.data.total
    } else {
      ElMessage.error(response.data.msg || '获取角色列表失败')
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('网络错误，请稍后重试')
  }
}

// 搜索
const search = () => {
  pagination.currentPage = 1
  queryRoleList()
}

// 新增角色
const addRole = () => {
  dialogTitle.value = '新增角色'
  formData.id = ''
  formData.name = ''
  formData.label = ''
  formData.remark = ''
  dialogVisible.value = true
}

// 编辑角色
const editRole = async (row) => {
  try {
    dialogTitle.value = '编辑角色'
    // 根据接口文档，使用GET /roles/{id}获取角色详情
    const response = await axios.get(`/roles/${row.id}`)
    if (response.data.code === 1) {
      Object.assign(formData, response.data.data)
      dialogVisible.value = true
    } else {
      ElMessage.error(response.data.msg || '获取角色详情失败')
    }
  } catch (error) {
    console.error('获取角色详情失败:', error)
    ElMessage.error('网络错误，请稍后重试')
  }
}

// 删除角色
const deleteRole = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色「${row.name}」吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 根据接口文档，使用DELETE /roles/{id}删除角色
    const response = await axios.delete(`/roles/${row.id}`)
    if (response.data.code === 1) {
      ElMessage.success('删除成功')
      queryRoleList() // 重新查询列表
    } else {
      ElMessage.error(response.data.msg || '删除失败')
    }
  } catch (error) {
    if (error.response) {
      // 接口返回错误，但不是用户取消
      if (error.response.data) {
        ElMessage.error(error.response.data.msg || '删除失败')
      }
    }
    // 用户取消删除不显示错误
  }
}

// 保存角色
const saveRole = async () => {
  if (!formData.name) {
    ElMessage.warning('请输入角色名称')
    return
  }
  if (!formData.label) {
    ElMessage.warning('请输入角色标识')
    return
  }
  
  try {
    if (formData.id) {
      // 编辑 - PUT /roles
      const response = await axios.put('/roles', {
        id: formData.id,
        name: formData.name,
        label: formData.label,
        remark: formData.remark,
        createTime: formData.createTime,
        updateTime: formData.updateTime
      })
      if (response.data.code === 1) {
        ElMessage.success('修改成功')
        dialogVisible.value = false
        queryRoleList() // 重新查询列表
      } else {
        ElMessage.error(response.data.msg || '修改失败')
      }
    } else {
      // 新增 - POST /roles
      const response = await axios.post('/roles', {
        name: formData.name,
        label: formData.label,
        remark: formData.remark
      })
      if (response.data.code === 1) {
        ElMessage.success('新增成功')
        dialogVisible.value = false
        queryRoleList() // 重新查询列表
      } else {
        ElMessage.error(response.data.msg || '新增失败')
      }
    }
  } catch (error) {
    console.error('保存角色失败:', error)
    ElMessage.error('网络错误，请稍后重试')
  }
}

// 分页处理
const handlePageChange = () => {
  queryRoleList()
}

// 格式化时间显示
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  // 转换ISO格式时间为本地时间格式
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 组件挂载时加载数据
onMounted(() => {
  queryRoleList()
})
</script>

<template>
  <div class="role-management">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :model="searchForm" label-width="80px" inline>
        <el-form-item label="角色名称">
          <el-input v-model="searchForm.name" placeholder="请输入角色名称" style="width: 200px" />
        </el-form-item>
        <el-form-item label="角色标识">
          <el-input v-model="searchForm.label" placeholder="请输入角色标识" style="width: 200px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">搜索</el-button>
          <el-button @click="resetForm">清空</el-button>
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="addRole" style="margin-left: 10px">
        <el-icon><Plus /></el-icon>
        添加角色
      </el-button>
    </div>
    
    <!-- 表格 -->
    <el-table :data="tableData" style="width: 100%">
      <el-table-column type="index" :index="indexMethod" label="序号" width="80" align="center" />
      <el-table-column prop="name" label="角色名称" />
      <el-table-column prop="label" label="角色标识" />
      <el-table-column prop="remark" label="备注" />
      <el-table-column label="创建时间">
        <template #default="scope">
          {{ formatDateTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="最后修改时间">
        <template #default="scope">
          {{ formatDateTime(scope.row.updateTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template #default="scope">
          <el-button type="primary" size="small" @click="editRole(scope.row)">
            <el-icon><Edit /></el-icon>
            修改
          </el-button>
          <el-button type="danger" size="small" @click="deleteRole(scope.row)" style="margin-left: 10px">
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handlePageChange"
        @current-change="handlePageChange"
      />
    </div>
    
    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
      <el-form :model="formData" label-width="120px">
        <el-form-item label="角色名称" prop="name" :required="true">
          <el-input v-model="formData.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色标识" prop="label" :required="true">
          <el-input v-model="formData.label" placeholder="请输入角色标识" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" placeholder="请输入备注信息" type="textarea" rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveRole">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.role-management {
  padding: 20px;
}

.search-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.text-primary {
  color: #409eff;
  cursor: pointer;
}

.text-danger {
  color: #f56c6c;
  cursor: pointer;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>
